<script setup>
import { ref, defineExpose } from 'vue';
import { imgUrl } from '../../utils/global';
import { userLoginApi } from '../../api/user';
import { useUserStore } from '../../store/user';

const popup = ref();
const userStore = useUserStore();
const isAgreed = ref(false);

const requestLogin = () => {
    popup.value.open();
};
const jumpDoc=(type)=>{
	console.log(type)
	uni.navigateTo({
		url:"/pages/webview/doc?type="+type
	})
}
const login = (event) => {
	// 检查是否同意协议
	if (!isAgreed.value) {
		uni.showToast({
			title: '请先同意用户协议和隐私政策',
			icon: 'none'
		});
		return;
	}

	const iv = event.detail.iv;
	const encryptedData = event.detail.encryptedData;
	uni.getProvider({
		service: 'oauth',
		success: (res) => {
			if(!res.provider.includes('weixin')) {
				console.error('provider not fount', res.provider);
				uni.showToast({
					title: '微信授权失败',
					icon: 'error'
				});
				return;
			}
			uni.login({
				provider: 'weixin',
				success: async (res) => {
					try {
						const results = await userLoginApi({
							iv: iv,
							encryptedData: encryptedData,
							code: res.code
						});
						userStore.token = results.token;
						userStore.userInfo = {
							id: results.userInfo['id'],
							avatar: results.userInfo['avatar'],
							nickname: results.userInfo['nickname'],
							phonenumber: results.userInfo['phone']
						};
						popup.value.close();
					} catch (error) {
						console.error('userLogin error', error);
						uni.showToast({
							title: '登录失败',
							icon: 'error'
						});
					}
				},
				fail: (error) => {
					console.error('login error', error);
					uni.showToast({
						title: '登录失败',
						icon: 'error'
					});
				}
			})
		},
		fail: (error) => {
			console.error('getProvider error', error);
			uni.showToast({
				title: '微信授权失败',
				icon: 'error'
			});
		}
	})
}

defineExpose({
    requestLogin
})

</script>

<template>
    <uni-popup ref="popup" type="bottom" border-radius="16rpx 16rpx 0 0" :safe-area="false">
        <view class="login-form">
            <image class="login-close" :src="imgUrl('/static/img/icons/close.png')" mode="aspectFill" @click="popup.close()" />
            <image class="login-bottom" :src="imgUrl('/static/img/imgs/bottom.png')" mode="aspectFill" />
            <image class="login-logo" :src="imgUrl('/static/img/imgs/logo.png')" mode="aspectFill" />
            <button class="login-button" open-type="getPhoneNumber" @getphonenumber="login">手机号快捷登录</button>
            <view class="login-row" style="z-index:999">
                <label @click="isAgreed = !isAgreed">
                    <radio :checked="isAgreed" activeBackgroundColor="#FF7F36" />
                    我已阅读并同意
                    <text @click.stop="jumpDoc(2)">《用户协议》</text>
                    和
                    <text @click.stop="jumpDoc(1)">《隐私政策》</text>
                </label>
            </view>
        </view>
    </uni-popup>
</template>

<style src="./style.scss" scoped />